import React, { useCallback, useState } from 'react';
import { parseSync, NodeList } from 'subtitle';

interface DragDropSubtitleProps {
  value?: NodeList;
  onChange?: (content: NodeList, fileName?: string) => void;
  accept?: string;
}

const DragDropSubtitle: React.FC<DragDropSubtitleProps> = ({
  value,
  onChange,
  accept = '.srt,.ass,.txt',
}) => {
  const [isDragging, setIsDragging] = useState(false);
  const [fileName, setFileName] = useState('');

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setIsDragging(true);
    } else if (e.type === 'dragleave') {
      setIsDragging(false);
    }
  }, []);

  const handleDrop = useCallback(
    async (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDragging(false);

      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
        await processFile(e.dataTransfer.files[0]);
      }
    },
    [onChange]
  );

  const handleFileChange = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files && e.target.files.length > 0) {
        await processFile(e.target.files[0]);
      }
    },
    [onChange]
  );

  const processFile = useCallback(
    async (file: File) => {
      try {
        const content = await file.text();
        setFileName(file.name);
        const nodes = parseSync(content);
        console.log(nodes);
        
        onChange?.(nodes, file.name);
      } catch (error) {
        console.error('Error reading file:', error);
        setFileName('');
      }
    },
    [onChange]
  );

  return (
    <div
      className={`relative border-2 border-dashed rounded-lg p-4 ${
        isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
      }`}
      onDragEnter={handleDrag}
      onDragOver={handleDrag}
      onDragLeave={handleDrag}
      onDrop={handleDrop}
    >
      <input
        type="file"
        id="file-upload"
        accept={accept}
        className="hidden"
        onChange={handleFileChange}
      />
      <label
        htmlFor="file-upload"
        className="flex flex-col items-center justify-center cursor-pointer"
      >
        <div className="text-center">
          <p className="text-sm text-gray-600">
            拖拽字幕文件到此处或
            <span className="text-blue-600">点击选择文件</span>
          </p>
          <p className="text-xs text-gray-500 mt-1">
            支持格式: {accept.replace(/\./g, '')}
          </p>
        </div>
      </label>
      {fileName && (
        <div className="mt-2 flex items-center text-sm text-green-600">
          <svg
            className="w-4 h-4 mr-1"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M5 13l4 4L19 7"
            />
          </svg>
          {fileName}
        </div>
      )}
    </div>
  );
};

export default DragDropSubtitle;
